package org.misty.seckill.interceptor;

import org.misty.seckill.redis.SessionKey;
import org.misty.seckill.service.LoginService;
import org.misty.seckill.util.ServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Deprecated
@Component
public class PreprocessInterceptor implements HandlerInterceptor {
  @Autowired
  private LoginService loginService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    var token = ServletUtil.readSessionToken(request);
    var user = loginService.getByToken(token);
    if (user != null) {
      request.setAttribute("token", token);
      request.setAttribute("user", user);
      loginService.keepAlive(token, user); // 刷新redis
      ServletUtil.writeSessionToken(response, token, SessionKey.TOKEN.getExpiryInSec(), "/");
    }
    return true;
  }
}
